﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using System.Data.SqlClient;

namespace ivvponderadorsInsert
{
    public partial class Insert : System.Web.UI.Page
    {
        protected MetaTable table;

        protected void Page_Init(object sender, EventArgs e)
        {
            DynamicDataManager1.RegisterControl(DetailsView1);
            Session["jadefiniufoco"] = "Nao"; 
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            table = DetailsDataSource.GetTable();
            Title = table.DisplayName;

            ContentPlaceHolder ph = (ContentPlaceHolder)Page.Master.FindControl("ContentPlaceHolder1");
            UpdatePanel up = ph.FindControl("UpdatePanel1") as UpdatePanel;

            DetailsView dt = up.FindControl("DetailsView1") as DetailsView;


            //Control ct = new Control(); 
            foreach (Control ct in dt.Controls)
            {

                object test;
                test = ct; //Set a breakpoint or watch window here and for each of the controls see which one gives you nothing

                if (ct.ToString() == "LiteralControlSystem.Web.UI.WebControls.TextBox")
                {
                    ct.Focus();
                    break;
                }
            }
        }

        protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            if (e.CommandName == DataControlCommands.CancelCommandName)
            {
                Response.Redirect(table.ListActionPath);
            }
        }

        protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            //if (e.Exception == null || e.ExceptionHandled)
            //{
            //    Response.Redirect(table.ListActionPath);
            //}

            if (e.Exception == null || e.ExceptionHandled)
            {

                //Usuario Cadastrado. Resgatar seu código, abre a conecção com o banco de dados, para puxar essa informação.                
                SqlConnection sqlc = new SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqlc.Open();

                //select no maior codigoUsuario na tabela usuario
                string sql = "Select MAX(codigoPonderador) AS codigoPonderador from Ponderador";

                SqlCommand cmdPonderador = new SqlCommand(sql, sqlc);
                SqlDataReader drPonderadors = cmdPonderador.ExecuteReader();

                string codigoPonderadorMax = "";

                if (drPonderadors.HasRows)
                {
                    while (drPonderadors.Read())
                    {
                        codigoPonderadorMax = drPonderadors["codigoPonderador"].ToString();
                    }
                }

                cmdPonderador.Dispose();
                drPonderadors.Close();

                sqlc.Close();


                string validarPassagem = "sim";

                System.Data.SqlClient.SqlConnection sqle = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                sqle.Open();

                string sqlPegarL = "select * from Ponderador where codigoPonderador = " + codigoPonderadorMax;

                System.Data.SqlClient.SqlCommand cmdPegarL = new System.Data.SqlClient.SqlCommand(sqlPegarL, sqle);
                System.Data.SqlClient.SqlDataReader drPegarL = cmdPegarL.ExecuteReader();
                drPegarL.Read();

                string descricaoPonderador = drPegarL["descricaoPonderador"].ToString();

                cmdPegarL.Dispose();
                drPegarL.Close();


                string descricaoPonderadors = "";
                string codigoPonderador = "";

                string sqls = "select * from Ponderador";

                System.Data.SqlClient.SqlCommand cmdListar = new System.Data.SqlClient.SqlCommand(sqls, sqle);
                System.Data.SqlClient.SqlDataReader drListar = cmdListar.ExecuteReader();

                if (drListar.HasRows)
                {
                    while (drListar.Read())
                    {
                        codigoPonderador = drListar["codigoPonderador"].ToString();
                        descricaoPonderadors = drListar["descricaoPonderador"].ToString();

                        descricaoPonderador = descricaoPonderador.ToUpper();
                        descricaoPonderadors = descricaoPonderadors.ToUpper();

                        if (codigoPonderador != codigoPonderadorMax && descricaoPonderadors.Equals(descricaoPonderador))
                        {
                            SqlConnection sqlDelMaquina = new SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                            sqlDelMaquina.Open();

                            string sqlDeletar = "delete from Ponderador where codigoPonderador = " + codigoPonderador + "";

                            SqlCommand deletarDetalhe = new SqlCommand(sqlDeletar, sqlDelMaquina);
                            deletarDetalhe.ExecuteNonQuery();

                            sqlDelMaquina.Close();

                            validarPassagem = "nao";

                            Response.Redirect("Insert.aspx?informacao=sim");
                        }
                    }
                }

                cmdListar.Dispose();
                drListar.Close();
                sqle.Close();


                if (validarPassagem == "sim")
                {



                    //Vamos gravar o registro da ação: log de atividades

                    string data = DateTime.Now.ToString("dd/MM/yyyy");

                    string hora = DateTime.Now.ToString("HH:mm:ss tt");

                    string sqlInserirLog = "insert into log (codigoUsuario, descricaoLog, codigoEntidadeLog, dataLog, horaLog) values (" + Session["codigoUsuario"].ToString();

                    sqlInserirLog = sqlInserirLog + ", 'Cadastro de Ponderador', " + codigoPonderadorMax + ", '" + data + "', '" + hora + "')";

                    SqlConnection sqlLog = new SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
                    sqlLog.Open();

                    SqlCommand inserirLog = new SqlCommand(sqlInserirLog, sqlLog);
                    inserirLog.ExecuteNonQuery();

                    inserirLog.Dispose();
                    sqlLog.Close();

                    //Gravação finalizada


                    Response.Redirect(table.ListActionPath);
                }
                else
                {

                }

            }
        }
    }
}
